package gdut.imis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import gdut.imis.domain.FileType;
import gdut.imis.domain.Manager;
import gdut.imis.domain.User;
import gdut.imis.enums.ManagerEnum;
import gdut.imis.mapper.ManagerMapper;
import gdut.imis.mapper.UserMapper;
import gdut.imis.vo.UserLoginVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author JiaFu
 * @Date 2023/4/11 12:50
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ManagerMapper managerMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserLoginVo userLogin = null;
        //查询普通用户
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getIdCard, username);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        //查询管理员
        LambdaQueryWrapper<Manager> managerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        managerLambdaQueryWrapper.eq(Manager::getPhone, username);
        Manager manager = managerMapper.selectOne(managerLambdaQueryWrapper);
        if (Objects.isNull(user) && Objects.isNull(manager)) {
            throw new RuntimeException("账号或密码错误");
        }
        if (Objects.isNull(user)) {//管理员
            userLogin = new UserLoginVo(manager, true, null);
            ManagerEnum managerType = manager.getType();
            userLogin.setPermissions(Arrays.asList(managerType.toString()));
            return userLogin;
        }
        //普通用户
        userLogin = new UserLoginVo(user, false, null);
        //todo 根据用户查询权限信息，封装到UserLogin中
        List<FileType> permissions = userMapper.getPermissions(user.getId());
        List<String> fileWritePermissions = permissions.stream().
                map(fileType -> StringUtils.uncapitalize(fileType.getType()))
                .collect(Collectors.toList());
        userLogin.setPermissions(fileWritePermissions);
        return userLogin;
    }
}
